﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TiTi.tea.DAL;
using TiTi.tea.Model;

namespace TiTi.tea.BLL
{
   
    public class UsreinfoBLL
    {
        public UserInfoDAL udal=new UserInfoDAL();
        public IEnumerable<UserInfo> Query(string UserName,out int Total,  int PageSize = 10, int PageIndex = 1)
        {
            var data = udal.GetAll();
            Total = data.Count();
            if (!string.IsNullOrEmpty(UserName))
            {
                data = data.Where(o=> o.UserName.Contains(UserName));
            }          
            return data.OrderBy(o => o.CreateTime).Skip(PageSize * (PageIndex - 1)).Take(PageSize);
        }

        public UserInfo Get(int id)
        {
            return udal.GetOne(o=>o.Id == id);
        }

        public bool Update(UserInfo entity)
        {
            return udal.Update(entity);
        }

        public bool Add(UserInfo entity)
        {
            return udal.Add(entity);
        }

        public bool Delete(int id)
        {
            UserInfo entity = new UserInfo();
            entity.Id = id;
            udal._dbContext.Entry(entity).State = System.Data.Entity.EntityState.Unchanged;
            entity.IsDelete = 1;
            return udal.SaveChanges();
        }


         public bool Impower(int userid, int[] roleIds)
        {
            UserRoleDAL userRoleDal = new UserRoleDAL();
            var oldRoles = userRoleDal.GetAll(o=>o.UserId==userid);
            foreach (var item in oldRoles)
            {
                item.IsDelete = 1;
            }

            foreach (var item in roleIds)
            {
                userRoleDal.Add(new UserRole()
                {
                    UserId = userid,
                    RoleId= item,
                    CreateTime= DateTime.Now,
                    IsDelete= 0,
                },false);
            }

            return userRoleDal.SaveChanges();
        }

        public IEnumerable<UserInfo> Getall()
        {
            return udal.GetAll();
        }

        public IEnumerable<UserRole> YesImpower(int userid)
        {
            UserRoleDAL userRoleDAL = new UserRoleDAL();
            return userRoleDAL.GetAll(o=>o.UserId==userid&&o.IsDelete==0);
        }
    }
}
